class Installation < ActiveRecord::Base
  
  include DynamicDefaultScoping
  
  validates :order_item_id,
    :presence => true

  validates :installed_count,
    :numericality => {
      :greater_than_or_equal_to => 0
    }
  validates :has_been_sent_to_installer_count,
    :numericality => {
      :greater_than_or_equal_to => 1
    }
    
  belongs_to :order_item
  has_many :feeds, :dependent => :destroy, :order => 'position asc'
  belongs_to :feed
  belongs_to :updated_by_user, :class_name => 'User', :foreign_key => :updated_by_user_id

  default_scope :current_enterprise,lambda {where(:enterprise_id => Enterprise.current_id )}
  scope :has_been_sent_to_installer, lambda{where( 'feeds.type in (?)',['Feed::InstallCreated']).includes(:feed)}

  # 安装完成
  scope :over, lambda{where( 'feeds.type = ?','Feed::Installed').includes(:feed)}
    
  after_create do |install|
    install.update_attribute :feed, Feed::InstallCreated.create!(
      :order_item_id => install.order_item_id,
      :installation_id => install.id)
  end

  before_save do |install|
    install.updated_by_user_id = User.current_id if install.changed?
  end

  after_update do |install|
    install.order_item.reset_after_serviced_cost!
  end

  after_save do |install|
    install.order_item.order.update_attribute(:installed_on, install.installed_on) if install.order_item.order.installed_on.nil? or install.order_item.order.installed_on < install.installed_on
    install.order_item.order.reset_gathered_balance!
  end
  
  after_destroy do |install|
    install.order_item.order.reset_gathered_balance!
  end

  def self.gathered_balance(order_id)
    where('order_items.order_id = ?', order_id).includes(:order_item).sum(:gathered_balance)
  end

  def update_gathered_balance!
    update_attributes :gathered_balance => 0
  end

  def update_installed_cost!
    update_attributes :installed_cost => 0
  end

  def update_installed_count!
    update_attributes :installed_count => 0
  end

  # 设置状态为 安装完成
  def installed!
    update_attributes :feed => Feed::Installed.create!(
        :order_item_id => order_item.id,
        :installation_id => id)
  end

  # 设置状态为 安装完成
  def install_unfinished!
    update_attributes :feed => Feed::InstallUnfinished.create!(
        :order_item_id => order_item.id,
        :installation_id => id)
  end

  def can_destroy?
    feeds.each do |feed|
      if feed.is_a?(Feed::Installed) || feed.is_a?(Feed::InstallUnfinished)
        return false
      end
    end
    return true
  end
  
  def reset_feed!
    update_attributes :feed_id => Feed.where(:installation_id => id).last.try(:id)
  end

end
